﻿using IOP.ISEA;
using IOP.SgrA;
using IOP.SgrA.ECS;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace VkSample91
{
    [ModulePriority(ModulePriority.Assets)]
    public class AssetsModule : VulkanModule, ISceneModule
    {
        private readonly ILogger<AssetsModule> _Logger;

        public AssetsModule(ILogger<AssetsModule> logger)
        {
            _Logger = logger;
        }

        public Scene Scene { get; set; }

        protected override async Task Load(VulkanGraphicsManager graphicsManager)
        {
            try
            {
                var basePath = AppContext.BaseDirectory;
                var modelsPath = Path.Combine(basePath, "Assets", "Models");
                var texPath = Path.Combine(basePath, "Assets", "Textures");
                graphicsManager.TryGetRenderGroup("OIT", out IRenderGroup oitGroup);
                graphicsManager.TryGetRenderGroup("Present", out IRenderGroup presentGroup);
                var lDevice = graphicsManager.VulkanDevice;

                ISEADocument document = new ISEADocument();
                await document.Load(Path.Combine(AppContext.BaseDirectory, "test91.isea"));
                var renders = await graphicsManager.CreateRenderObjectsFromISEA<RenderObject>(document);
                var rectArchetype = ContextManager.CreateArchetype(new TransformComponent(), new RectComponent());
                var treeArchetype = ContextManager.CreateArchetype(new TransformComponent(), new TreeComponent());
                var noneArchetype = ContextManager.CreateArchetype(new NoneComponent());

                foreach(var item in renders)
                {
                    if(item.Name == "Tree")
                    {
                        ContextManager.CreateContexts(9, treeArchetype, oitGroup, item);
                    }
                    else if(item.Name == "Desert")
                    {
                        ContextManager.CreateContexts(1, rectArchetype, oitGroup, item);
                    }
                    else if(item.Name == "None")
                    {
                        ContextManager.CreateContexts(1, noneArchetype, presentGroup, item);
                    }
                }

            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message + "\r\n" + e.StackTrace);
            }
        }

        protected override Task Unload(VulkanGraphicsManager manager)
        {
            return Task.CompletedTask;
        }
    }
}
